<template>
  <div class="profile-container">
    <!-- 头像和基本信息 -->
    <div class="profile-header">
      <!-- 头像上传区域 -->
      <div class="avatar-uploader">
        <el-upload
         class="avatar-upload"
         :show-file-list="false"
         :on-success="handleAvatarSuccess"
         :before-upload="beforeAvatarUpload"
         :http-request="customUpload" 
        >
          <img v-if="form.profileImage" :src="form.profileImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><User /></el-icon>
          <div class="upload-mask">
            <el-icon><Upload /></el-icon>
            <span>点击上传</span>
          </div>
        </el-upload>
      </div>

      <!-- 基本信息 -->
      <div class="base-info">
        <h2>{{ form.fullName }}的个人中心</h2>
        <el-tag type="success">{{ form.role === 'ADMIN' ? '管理员' : '普通用户' }}</el-tag>
        <div class="create-time">注册时间：{{ formatDate(form.addTime) }}</div>
      </div>
    </div>

    <!-- 详细信息表单 -->
    <el-form 
      ref="formRef"
      :model="form" 
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          show-password
          placeholder="输入新密码（留空不修改）"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>

      <el-form-item label="真实姓名" prop="fullName">
        <el-input v-model="form.fullName" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import axios from 'axios'
import { User, Upload } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const token = localStorage.getItem('token');
const formRef = ref<FormInstance>()
const form = ref({
  id: '',
  username: '',
  password: '', // 新增密码字段
  phone: '',
  fullName: '',
  gender: '',
  profileImage: '',
  role: '',
  addTime: null as Date | null
})

// 上传相关配置
// 添加自定义上传方法
const customUpload = async (options: any) => {
  const formData = new FormData();
  formData.append('avatar', options.file); // 参数名需与后端 @RequestPart("avatar") 一致

  try {
    const response = await axios.put(
      `http://localhost:8080/user/update/${localStorage.getItem('userId')}`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }
    );
    options.onSuccess(response.data); // 触发 on-success 回调
  } catch (error) {
    options.onError(error);
  }
};

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  fullName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 加载用户数据
const loadUserData = async () => {
  try {
    const userId = localStorage.getItem('userId');
    
    if (!userId || !token) {
      ElMessage.error('请重新登录');
      return router.push('/login');
    }

    const { data } = await axios.get(`/user/byId/${userId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    form.value = {
      ...data,
      profileImage: data.profileImage 
    ? 'https://lost-xin.oss-cn-beijing.aliyuncs.com/avatars' + data.profileImage // 替换为实际 OSS 地址
    : '',
      password: '' // 密码字段单独处理
    };
    
  } catch (error: any) {
  const message = error.response?.data?.message || '请求失败'
  ElMessage.error(`数据加载失败: ${message}`)
}
}

// 头像上传处理
const handleAvatarSuccess = (response: any) => {
  if (response.profileImage) {
    form.value.profileImage = response.profileImage + '?t=' + Date.now();
    localStorage.setItem('profileImage', response.profileImage); // 更新本地存储
    ElMessage.success('头像更新成功');
  }
};

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
  }
  return isImage && isLt2M
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    
    const formData = new FormData()
    const userId = localStorage.getItem('userId')
    
    // 添加可修改字段
    formData.append('username', form.value.username)
    formData.append('password', form.value.password)
    formData.append('fullName', form.value.fullName)
    formData.append('gender', form.value.gender)
    formData.append('phone', form.value.phone)

    // 发送请求
    const response = await axios.put(`/user/update/${userId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`  // 在请求头中添加 Token
 
      }
    })

    if (response.status === 200) {
      ElMessage.success('信息更新成功');
      localStorage.setItem('username', form.value.username); // 新增此行
      loadUserData();
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '更新失败')
  }
}

// 重置表单
const resetForm = () => {
  loadUserData()
}

// 日期格式化
const formatDate = (date: Date | null) => {
  return date ? new Date(date).toLocaleString() : ''
}

onMounted(() => {
  loadUserData()
})

// 全局请求拦截器
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
</script>
  
  <style scoped>
  .profile-container {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
  }
  
  .profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
  }
  
  .avatar-uploader {
    position: relative;
    width: 120px;
    height: 120px;
    margin-right: 40px;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;
  }
  
  .avatar-upload:hover .upload-mask {
    opacity: 1;
  }
  
  .avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    opacity: 0;
    transition: opacity 0.3s;
  }
  
  .avatar-uploader-icon {
    width: 100%;
    height: 100%;
    font-size: 40px;
    color: #909399;
    background: #f0f2f5;
  }
  
  .base-info h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
  }
  </style>